package cn.hsw.component.auth.jwt;


import cn.hsw.component.auth.constant.AuthConstant;
import cn.hsw.component.core.util.IdUtil;
import cn.hsw.component.redis.RedisUtil;
import cn.hsw.component.web.util.ServletUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.subject.Subject;

/**
 * jwt 工具类
 * @author 李子木
 */
public class JwtUtil {

    /**
     * 校验token
     * @param token token
     * @param phone 手机号
     * @param salt 密码
     * @return
     * 校验token时去token池中校验时间。如正常则续期 @TODO
     */
    public static boolean verify(String token,String phone,String salt){
        try{
            Algorithm algorithm = Algorithm.HMAC256(salt);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("phone",phone).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 生成token
     * @param phone 手机号
     * @return
     *
     */
    public static String sign(String phone,String salt){
        Algorithm algorithm = Algorithm.HMAC256(salt);
        String token = JWT.create()
                .withClaim("phone",phone)
                .withClaim("random_number", IdUtil.generate())
                .sign(algorithm);
        return token;
    }

    /**
     * 根据token获取手机号
     * @param token  jwt token
     * @return
     */
    public static String getPhone(String token){
        try {
            //token = checkToken(token);
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("phone").asString();
        }catch (Exception e){
            return "";
        }
    }
    public static String getPhone(){
        String token = ServletUtil.getRequest().getHeader(AuthConstant.TOKEN_HEADER_NAME);
        token = checkToken(token);
        return getPhone(token);
    }

    public static void login(String token) {
        Subject subject = SecurityUtils.getSubject();
        JwtToken jwtToken = new JwtToken(token);
        subject.login(jwtToken);
    }

    public static String checkToken(String token){
        if(token.startsWith(AuthConstant.TOKEN_PREFIX)
                ||token.startsWith(AuthConstant.TOKEN_PREFIX.toUpperCase())
                ||token.startsWith(AuthConstant.TOKEN_PREFIX.toLowerCase())){
            return token.substring(AuthConstant.TOKEN_PREFIX.length());
        }else{
            throw new IncorrectCredentialsException("token无效");
        }
    }
}
